package com.gxcc3.ygps.system.service.impl;

import com.gxcc3.ygps.common.core.domain.TreeEntity;
import com.gxcc3.ygps.common.core.domain.entity.SysCheckGoodsCategory;
import com.gxcc3.ygps.system.mapper.SysCheckGoodsCategoryMapper;
import com.gxcc3.ygps.system.service.ISysCheckGoodsCategoryService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class SysCheckGoodsCategoryServiceImpl implements ISysCheckGoodsCategoryService {

    @Resource
    SysCheckGoodsCategoryMapper goodsCategoryMapper;


    /**
     * 获取商品分类树
     * @return 商品分类树
     */
    @Override
    public List<SysCheckGoodsCategory> selectGoodsCategoryList() {
        return goodsCategoryMapper.selectGoodsCategoryList();
    }

    /**
     * 构建商品分类树
     * @param list 商品分类列表
     * @return 商品分类树
     */
    @Override
    public List<TreeEntity> buildGoodsCategoryTree(List<SysCheckGoodsCategory> list) {
        Set<Long> ids = list.stream()
                .map(SysCheckGoodsCategory::getId)
                .collect(Collectors.toSet());

        List<SysCheckGoodsCategory> collect = list.stream()
                .filter(m -> !ids.contains(m.getParentId()))
                .peek(m -> m.setChildren(getChildrenList(m, list)))
                .collect(Collectors.toList());
        return collect.stream().map(TreeEntity::new).collect(Collectors.toList());
    }


    private List<SysCheckGoodsCategory> getChildrenList(SysCheckGoodsCategory root, List<SysCheckGoodsCategory> all) {
        return all.stream().filter(m -> Objects.equals(m.getParentId(), root.getId())).peek(
                (m) -> m.setChildren(getChildrenList(m, all))
        ).collect(Collectors.toList());
    }
}
